'use client';

import { type ChangeEvent, type FormEvent, useEffect, useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { clientQueryAllSection, updatePostTemplate } from '@/services/api';
import diff from 'microdiff';
import type { IDifference, IPostTemplate } from '@/interfaces';
import { ISectionClient } from '@/interfaces';
import type { TBody } from '@/types';
import useToast from '@/hooks/useToast';
import { getDiffData, getFilterData, isEmpty } from '@/lib/tool';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';

export default function UpdatePostTemplateInfo({
  details,
}: {
  details: IPostTemplate;
}) {
  const { show } = useToast();
  const [form, setForm] = useState<{
    name?: string;
    overview?: string;
    sort?: number;
    sectionId?: string;
  }>({
    name: '',
    overview: '',
    sort: 0,
    sectionId: '',
  });
  const [differenceData, setDifferenceData] = useState<IDifference[]>([]);
  const queryClient = useQueryClient();

  const clientQueryAllSectionQuery = useQuery(
    ['/forum', '/sections', '/client'],
    async () => {
      return (await clientQueryAllSection()) as ISectionClient[];
    },
  );

  const updatePostTemplateMutation = useMutation(
    async (
      variables: TBody<{
        name?: string;
        overview?: string;
        content?: string;
        sort?: number;
        sectionId?: number;
      }>,
    ) => {
      await updatePostTemplate(variables);
      await queryClient.invalidateQueries(['/forum', '/templates', details.id]);
    },
  );

  useEffect(() => {
    if (details) {
      setForm({
        name: details.name,
        overview: details.overview || '',
        sort: details.sort,
        sectionId: details.section.id + '',
      });
    }
  }, [details]);
  useEffect(() => {
    if (details) {
      const differences = diff(
        {
          name: details.name,
          overview: details.overview || '',
          sort: details.sort,
          sectionId: details.section.id + '',
        },
        {
          name: form.name,
          overview: form.overview,
          sort: form.sort,
          sectionId: form.sectionId,
        },
      );
      setDifferenceData(differences);
    }
  }, [form, details]);

  function onChangeForm(e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) {
    const name = e.target.name;
    const value = e.target.value;

    if (name === 'sort') {
      setForm({ ...form, sort: parseInt(value) });
    } else {
      setForm({ ...form, [name]: value });
    }
  }

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const body = getFilterData(getDiffData(differenceData));
      if (isEmpty(body)) {
        show({
          type: 'SUCCESS',
          message: '保存完成',
        });
        return;
      }

      await updatePostTemplateMutation.mutateAsync({
        id: details.id,
        data: body,
      });

      clearData();
      show({
        type: 'SUCCESS',
        message: '保存完成',
      });
    } catch (e) {
      updatePostTemplateMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function clearData() {
    setDifferenceData([]);
  }

  return (
    <div className="row">
      <div className="col">
        <form onSubmit={onClickSave} className="vstack gap-4">
          <div>
            <label className="form-label">名称</label>
            <input
              type="text"
              className="form-control"
              name="name"
              value={form.name}
              onChange={onChangeForm}
              aria-describedby="name"
              placeholder="请输入帖子模板名称"
            />
          </div>

          <div>
            <label className="form-label">概述</label>
            <input
              type="text"
              className="form-control"
              name="overview"
              value={form.overview}
              onChange={onChangeForm}
              aria-describedby="overview"
              placeholder="请输入帖子模板概述"
            />
          </div>

          <div>
            <label className="form-label">排序</label>
            <input
              min={0}
              type="number"
              className="form-control"
              name="sort"
              value={form.sort}
              onChange={onChangeForm}
              aria-describedby="sort"
              placeholder="请输入帖子模板排序"
            />
          </div>

          <div>
            <label className="form-label">版块</label>
            {clientQueryAllSectionQuery.data && (
              <select
                name="sectionId"
                value={form.sectionId}
                onChange={onChangeForm}
                className="form-select"
                placeholder="请选择版块"
              >
                <option disabled value="">
                  请选择版块
                </option>
                {clientQueryAllSectionQuery.data.map((item) => {
                  return (
                    <option key={item.id} value={item.id}>
                      {item.name}
                    </option>
                  );
                })}
              </select>
            )}

            {clientQueryAllSectionQuery.isError && (
              <Alert message={clientQueryAllSectionQuery.error} type="error" />
            )}

            {clientQueryAllSectionQuery.isLoading && <AlertLoad />}
          </div>

          <button
            type="submit"
            disabled={updatePostTemplateMutation.isLoading}
            className="btn btn-success w-25 my-4"
          >
            {updatePostTemplateMutation.isLoading && (
              <span
                className="spinner-border spinner-border-sm me-2"
                role="status"
                aria-hidden="true"
              ></span>
            )}
            更新
          </button>
        </form>
      </div>
    </div>
  );
}
